﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EIA.PM.DAL;

namespace EIA.PM.DAL.IBatis
{
    public class IBatisDaoFactory : IDaoFactory
    {
        public TDao Create<TDao>()
        {
            Type type = typeof(TDao);
            if (type.IsInterface)
            {
                type = this.GetType().Assembly.GetType(this.GetType().Namespace + "." + type.Name.Remove(0, 1));
            }
            if (null == type || type.Assembly != this.GetType().Assembly) throw new Exception("TDao is not in the assembly: " + this.GetType().Assembly.FullName);
            if (!_cache.ContainsKey(type))
            {
                lock (_lockObj)
                {
                    if (!_cache.ContainsKey(type))
                    {
                        TDao dao = (TDao)type.Assembly.CreateInstance(type.FullName);
                        _cache.Add(type, dao);
                    }
                }
            }
            return (TDao)_cache[type];
        }

        private Dictionary<Type, object> _cache = new Dictionary<Type, object>();
        private object _lockObj = new object();
    }
}
